import axios from "axios";
import store from "@/store";
import {Toast} from "vant";

axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
axios.defaults.baseURL = "http://192.168.0.234:9033/";

type Method = "get" | "GET" | "delete" | "DELETE" | "head"
  | "HEAD" | "options" | "OPTIONS" | "post" | "POST" | "put"
  | "PUT" | "patch" | "PATCH" | "link" | "LINK" | "unlink" | "UNLINK"

export async function request(url: string, method: Method, data: {}) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      axios({url, data, method}).then((res) => {
        console.log(res);
        if (!res.data.success) {
          store.commit("showLoading", false);
          const message = res.data.err_msg ? res.data.err_msg : "请求失败";
          Toast.fail({message, duration: 1000});
          reject(res);
        } else {
          if (res.data.err_code === "1") {
            store.commit("showLoading", false);
            const message = res.data.err_msg === "COMMODITY_NOT_EXIST！" ? "暂无数据" : res.data.err_msg;
            Toast.fail({message, duration: 1000});
            reject(res);
          } else {
            store.commit("showLoading", false);
            resolve(res);
          }
        }
      }).catch(() => {
        //连接服务端失败
        store.commit("showLoading", false);
        Toast.fail({message: "请求异常!", duration: 1000});
        return;
      });
    }, 500);
  });
}

